//  1. 引入包
const express = require('express');
const expressStatic = require('express-static');
const slideRouter = require('./routes/slide');
const dbConnect = require('./utils/db/mongodbConnect');
const userRouter = require('./routes/user');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const viewRouter = require('./routes/views');
const childRouter = require('./routes/child');
const menRouter = require('./routes/men');
const womenRouter = require('./routes/women');
const mobileRouter = require('./routes/mobile');
const mainRouter=require('./routes/main');
//  2. 创建服务
var app = express();
app.listen(8081,function (err) {
    if(err){
        console.log("App is wrong!");
    }else{
        console.log("App is runing!");
    }
});
//  排除favicon.ico
app.use('/favicon.ico',function (req,res) {
    res.send('');
})
//  开启数据连接
dbConnect.dbConnect();
//  启用body-parser
app.use(bodyParser.urlencoded({extend:true}));
//  启用cookie
var keys = [];
for(var i=0;i<10000;i++){
    var str = 'abcd133%%^&' + Math.random(1000000);
    keys.push(str);
}
app.use(cookieParser());
app.use(cookieSession({
    name:'storeOnline',
    keys:keys,
    maxAge:20*60*1000
}))
//  应用路由
//  1. 主页index.html
app.use('/slide',slideRouter.router);
app.use('/user',userRouter.router);
app.use('/views',viewRouter.router);
app.use('/main',mainRouter.router);
//  2. 详情页
app.use('/child',childRouter.router);
app.use('/men',menRouter.router);
app.use('/women',womenRouter.router);
app.use('/mobile',mobileRouter.router);

//  起启页
app.use('/',function (req,res,next) {
    var options = {
        root:__dirname + '/www/',
        dotfiles:'deny',
        headers:{
            'x-timestamp':Date.now(),
            'x-sent':true
        }
    };
    var url = req.url;
    if (url.indexOf('/') == 0 && url.length > 1){
        next();
    }else{
        res.sendFile('index.html',options,function (err) {
            if(err){
                console.log("index.html is wrong!");
            }
        });
    }

});


//  3. 静态页面的访问
app.use(expressStatic('./www'));